﻿using System;
using System.ComponentModel;
using System.IO;
using System.Text;
using Watchdog.Properties;
using Watchdog.SupervisionService;

namespace Watchdog
{
    public class HistoryKeeper
    {
        private BackgroundWorker worker;

        public bool IsCleaningHistory {
            get { return worker.IsBusy; }
        }

        public HistoryKeeper()
        {
            worker = new BackgroundWorker();
        }


        public  void RegisterActivity(PalaceActivity activity)
        {

            if (Settings.Default.CollectDataOffline)
            {
                activity.Time = DateTime.Now;
                if(!IsCleaningHistory)
                    SaveToHistory(activity);
                else
                {
                    //TODO: Save to memory?
                }
            }
        }


        private  void SaveToHistory(PalaceActivity activity)
        {
            using (var file = new StreamWriter(Settings.Default.OffLogFilePath, true,Encoding.UTF8)){
                file.WriteLine(JsonUtil.Serialize(activity));
            }
        }

      

        public  void CleanOldRecords()
        {
            worker.DoWork += CleaningWork;
            worker.RunWorkerAsync();
            
        }

        private  void CleaningWork(object sender, DoWorkEventArgs e)
        { 
            var now = DateTime.Now;
            var daysLimit = Settings.Default.HistorySizeInDays;
            String line;
            string tempPath = Path.GetTempFileName();
            using (var reader = new StreamReader(Settings.Default.OffLogFilePath)){
                using (var writer = new StreamWriter(File.OpenWrite(tempPath))){
                    while ((line = reader.ReadLine()) != null){
                        PalaceActivity activity = JsonUtil.Deserialize<PalaceActivity>(line);
                        if ((now - activity.Time).TotalDays > daysLimit)
                            continue;
                        writer.WriteLine(line);
                    }
                }
            }
            if (File.Exists(tempPath))
            {
                File.Delete(Settings.Default.OffLogFilePath);
                File.Move(tempPath, Settings.Default.OffLogFilePath);
            }
        }

        public void FlushHitory()
        {
            
            String line;
            using (var reader = new StreamReader(Settings.Default.OffLogFilePath)){
                while ((line = reader.ReadLine()) != null){
                        PalaceActivity activity = JsonUtil.Deserialize<PalaceActivity>(line);

                    //Todo: Send activity (or by groups) to observer to store in database 
                    }
            }
            if (File.Exists(Settings.Default.OffLogFilePath)){
                File.Delete(Settings.Default.OffLogFilePath);
            }
        }
    }
}
